#include "threadPool.h"
int makeWorker(threadPool_t *pthreadPool){
    //创建若干个子线程
    for(int i = 0; i < pthreadPool->threadNum; ++i){
        pthread_create(&pthreadPool->tidArr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
//void *threadFunc(void *arg){
//    threadPool_t *pthreadPool = (threadPool_t *)arg;
//    while(1){
//        pthread_mutex_lock(&pthreadPool->taskQueue.mutex);
//        while(pthreadPool->taskQueue.queueSize == 0){
//            pthread_cond_wait(&pthreadPool->taskQueue.cond,&pthreadPool->taskQueue.mutex);
//        }
//        int netfd = pthreadPool->taskQueue.pFront->netfd;
//        taskDequeue(&pthreadPool->taskQueue);
//        pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
//        transFile(netfd);
//        close(netfd);
//        printf("child thread finished task!\n");
//    }
//}
void cleanupMutex(void *arg){
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    printf("unlock\n");
    pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
}
void *threadFunc(void *arg){
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    while(1){
        int netfd;
        pthread_mutex_lock(&pthreadPool->taskQueue.mutex);
        //pthread_cleanup_push(cleanupMutex,pthreadPool);
        if(pthreadPool->exitflag == 1){
            printf("I am going to die!\n");
            pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        while(pthreadPool->taskQueue.queueSize == 0){
            if(pthreadPool->exitflag == 1){
                printf("I am going to die!\n");
                pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
                pthread_exit(NULL);
            }
            pthread_cond_wait(&pthreadPool->taskQueue.cond,&pthreadPool->taskQueue.mutex);
        }
        netfd = pthreadPool->taskQueue.pFront->netfd;
        taskDequeue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
        //pthread_cleanup_pop(1);
        transFile(netfd);
        close(netfd);
        printf("child thread finished task!\n");
    }
}
